package com.amorcloud.pig.utils;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

import java.util.List;

/**
 * Created by Administrator on 2018/4/17.
 * 获取用户的地理位置
 */
public class GPSUtils {

    private static GPSUtils instance;
    private Context mContext;
    private LocationManager locationManager;

    private GPSUtils(Context context) {
        this.mContext = context;
    }

    public static GPSUtils getInstance(Context context) {
        if (instance == null) {
            instance = new GPSUtils(context);
        }
        return instance;
    }

    /**
     * 获取经纬度
     *
     * @return
     */
    /*public String getLngAndLat(*//*OnLocationResultListener onLocationResultListener*//*) {
        Log.d("leihuiming", "getLngAndLat");
        double latitude = 0.0;
        double longitude = 0.0;

        //mOnLocationListener = onLocationResultListener;
        Log.d("leihuiming", "getLngAndLat");
        String locationProvider = null;
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        Log.d("leihuiming", "providers = " + (providers != null ? providers.size() : "null"));
        for(String s : providers) {
            Log.d("leihuiming", "s= " + s);
        }
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else {
            Intent i = new Intent();
            i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(i);
            return null;
        }

        //获取Location
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Log.d("leihuiming", "no permission");
            return null;
        }
        Log.d("leihuiming", "getLastKnownLocation start");
        Location location = locationManager.getLastKnownLocation(locationProvider);
        Log.d("leihuiming", "getLastKnownLocation end   location = " + (location == null));
        if (location != null) {
            //不为空,显示地理位置经纬度
            if (mOnLocationListener != null) {
                mOnLocationListener.onLocationResult(location);
            }
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            Log.d("leihuiming", "GPSUtils = " + longitude + "," + latitude);
            return longitude + "," + latitude;
        }
        //监视地理位置变化
        locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
        return null;
    }*/
    public String getLngAndLat(/*OnLocationResultListener onLocationResultListener*/) {
        Log.d("leihuiming", "getLngAndLat");
        double latitude = 0.0;
        double longitude = 0.0;
        Location location = null;
        String locationProvider = null;
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        Log.d("leihuiming", "gps providers = " + locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));

        Criteria criteria = new Criteria();
        criteria.setCostAllowed(false);
        //设置位置服务免费
        criteria.setAccuracy(Criteria.ACCURACY_COARSE); //设置水平位置精度
        //getBestProvider 只有允许访问调用活动的位置供应商将被返回
        String providerName = locationManager.getBestProvider(criteria, true);
        Log.d("leihuiming", "best providerName = " + providerName);

        /*for(String s : providers) {
            Log.d("leihuiming", "s= " + s);
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return null;
            }
            location = locationManager.getLastKnownLocation(s);
            Log.d("leihuiming", "location = " + (location == null));
            if(location != null){
                //监视地理位置变化
                locationManager.requestLocationUpdates(s, 3000, 1, locationListener);
                break;
            }
        }*/
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, locationListener);
        locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 3000, 1, locationListener);

        if (location != null) {
            //不为空,显示地理位置经纬度
            if (mOnLocationListener != null) {
                mOnLocationListener.onLocationResult(location);
            }
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            Log.d("leihuiming", "GPSUtils = " + longitude + "," + latitude);
            return longitude + "," + latitude;
        }

        return null;
    }

    public LocationListener locationListener = new LocationListener() {

        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d("leihuiming", "GPSUtils onStatusChanged");
        }

        // Provider被enable时触发此函数，比如GPS被打开
        @Override
        public void onProviderEnabled(String provider) {
            Log.d("leihuiming", "GPSUtils onProviderEnabled");
        }

        // Provider被disable时触发此函数，比如GPS被关闭
        @Override
        public void onProviderDisabled(String provider) {
            Log.d("leihuiming", "GPSUtils onProviderDisabled");
        }

        //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        @Override
        public void onLocationChanged(Location location) {
            Log.d("leihuiming", "GPSUtils lon" + location.getLongitude());
            Log.d("leihuiming", "GPSUtils lat" + location.getLatitude());

            if (mOnLocationListener != null) {
                mOnLocationListener.OnLocationChange(location);
            }
        }
    };

    public void removeListener() {
        locationManager.removeUpdates(locationListener);
    }

    private OnLocationResultListener mOnLocationListener;

    public void setLocationListener(OnLocationResultListener listener) {
        this.mOnLocationListener = listener;
    }

    public interface OnLocationResultListener {
        void onLocationResult(Location location);

        void OnLocationChange(Location location);
    }
}
